package cn.gwm.utils;

import cn.gwm.flink.streaming.constant.ChargePredictFields;
import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author : GW00280745
 * @date : 2023/1/16 13:10
 * @description :
 * phoenix 连接池
 */
public class HBaseDataSource {

    private volatile static HBaseDataSource instance;
    private HBaseDataSource(){
        try {
            DruidDataSource dataSource = new DruidDataSource();
            Properties phoenixConf = new Properties();
            phoenixConf.setProperty("phoenix.schema.isNamespaceMappingEnabled", String.valueOf(true));
            dataSource.setConnectProperties(phoenixConf);
            //阿里云
            String phoenixUrl = ChargePredictFields.ins().confInfo.getOrDefault("phoenix.url","jdbc:phoenix:10.31.8.112,10.31.8.113,10.31.8.114:2181");
//            phoenixUrl ="jdbc:phoenix:10.31.8.112,10.31.8.113,10.31.8.114:2181"
            dataSource.setUrl(phoenixUrl);
            dataSource.setDriverClassName("org.apache.phoenix.jdbc.PhoenixDriver");
            // 设置连接池的初始大小
            dataSource.setInitialSize(3);
            // 设置连接池大小的下限
            dataSource.setMinIdle(1);
            // 设置连接池大小的上限
            dataSource.setMaxActive(20);
            dataSource.setTestWhileIdle(false);
            ds = dataSource;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static HBaseDataSource ins() {
        if (instance == null) {
            synchronized (HBaseDataSource.class) {
                if (instance == null) {
                    instance = new HBaseDataSource();
                }
            }
        }
        return instance;
    }

    /**
     * 获取连接
     */
    public Connection getConnection() throws SQLException {
        Connection connection = ds.getConnection();
        return connection;
    }

    /**
     * 释放资源
     */
    public void close( Connection conn){
        try {
            if (conn==null){return;}
            conn.close();//归还连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private DataSource ds ;
    /**
     * 获取连接池方法
     */
    public DataSource getDataSource(){
        return  ds;
    }
}
